﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Web.Security;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace ProjectStudy.Ajax
{
    /// <summary>
    /// RegisterLoginChangePwdFindPwd 的摘要说明
    /// </summary>
    public class RegisterLoginChangePwdFindPwd : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        private static DataTable dt1 = null;
        private static string username = null;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["action"];
            switch (action)
            {
                case "register": Register(context);
                    break;
                case "login": Login(context);
                    break;
                case "logout": Logout(context);
                    break;
                case "changepwd": ChangePWD(context);
                    break;
                case "findpwd": FindPWD(context);
                    break;
                case "getQuestion": context.Response.Write(GetQuestion(context));
                    
                    break;
            }
        }

        //获取问题列表
        private string GetQuestion(HttpContext context)
        {
            string sql = "select QuestionName from QuestionTable";
            DataTable dt = DBAccess.ExecuteDataTable(sql);
            return JsonConvert.SerializeObject(dt);
        }

        //注册   
        private void Register(HttpContext context)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();

            string username = context.Request["username"].ConvertObjToStr();
            string pwd = context.Request["pwd"].ConvertObjToStr();
            string sex = context.Request["sex"].ConvertObjToStr();
            string email = context.Request["email"].ConvertObjToStr();
            string group = "common";
            string question = context.Request["question"].ConvertObjToStr();
            string answer = context.Request["answer"].ConvertObjToStr();

            string sql1 = "select 1 from User2 where username=@username";
            string sql2 = "insert into User2(username,pwd,sex,[group],email,question,answer,registerTime) values(@username,@pwd,@sex,@group,@email,@question,@answer,@registerTime)";
            SqlParameter[] ps2 = { 
                                new SqlParameter("@username",username),
                                new SqlParameter("@pwd",MD5(pwd)),
                                new SqlParameter("@group",group),
                                new SqlParameter("@sex",sex),
                                new SqlParameter("@email",email),
                                new SqlParameter("@question",question),
                                new SqlParameter("@answer",answer),
                                new SqlParameter("@registerTime",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                                };
            DataTable dt = DBAccess.ExecuteDataTable(sql1, ps2[0]);

            if (dt.Rows.Count > 0)
            {
                dic.Add("status", "exist");
                context.Response.Write((new JavaScriptSerializer()).Serialize(dic));
            }
            else
            {
                int a = DBAccess.ExecuteNonQuery(sql2, ps2);
                if (a > 0)
                {
                    dic.Add("status", "success");
                    context.Response.Write((new JavaScriptSerializer()).Serialize(dic));
                }
            }
        }

        //登录
        private void Login(HttpContext context)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();

            string username = context.Request["username"];
            string pwd = context.Request["pwd"];
            string sql = "select [group],isActive,IsLock from User2 where username=@username and pwd=@pwd";
            SqlParameter[] ps = { 
                                new SqlParameter("@username",username),
                                new SqlParameter("@pwd",MD5(pwd))
                                };
            DataTable dt = DBAccess.ExecuteDataTable(sql, ps);
            if (dt.Rows.Count <= 0)
            {
                dic.Add("status", "usernameOrPwdErr");
            }
            else
            {
                if (dt.Rows[0]["isActive"].ConvertObjToStr() == "Y")
                {
                    if (dt.Rows[0]["isLock"].ConvertObjToStr() == "N")
                    {
                        context.Session["username"] = username;
                        string group = dt.Rows[0][0].ConvertObjToStr();
                        context.Session["group"] = group;
                        string sql2 = "select class from GroupClass where GroupName=@groupname";
                        SqlParameter ps2 = new SqlParameter("@groupname", group);
                        DataTable dt2 = DBAccess.ExecuteDataTable(sql2, ps2);
                        if (dt2.Rows.Count > 0)
                        {
                            context.Session["class"] = dt2.Rows[0][0].ConvertObjToStr();
                        }
                        dic.Add("status", "success");
                    }
                    else
                    {
                        dic.Add("status", "lock");
                    }
                }
                else
                {
                    dic.Add("status", "noActive");
                }
            }
            context.Response.Write((new JavaScriptSerializer()).Serialize(dic));
        }

        //注销
        private void Logout(HttpContext context)
        {
            context.Session["username"] = null;
            context.Session["class"] = null;
            context.Session["group"] = null;
        }

        //修改密码
        private void ChangePWD(HttpContext context)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string username = context.Session["username"].ConvertObjToStr();
            string oldpwd = context.Request["oldpwd"];
            string newpwd = context.Request["newpwd"];
            if (username != "")
            {
                string sql1 = "select 1 from User2 where username=@username and pwd=@pwd";
                SqlParameter[] ps1 = { 
                                 new SqlParameter("@username",username),
                                 new SqlParameter("@pwd",MD5(oldpwd))
                                 };
                DataTable dt = DBAccess.ExecuteDataTable(sql1, ps1);
                if (dt.Rows.Count <= 0)
                {
                    dic.Add("status", "oldPwdErr");
                    context.Response.Write((new JavaScriptSerializer()).Serialize(dic));
                }
                else
                {
                    string sql2 = "update User2 set pwd=@pwd where username=@username";
                    SqlParameter[] ps2 = { 
                                     new SqlParameter("@pwd",MD5(newpwd)),
                                     new SqlParameter("@username",username)
                                     };
                    int a = DBAccess.ExecuteNonQuery(sql2, ps2);
                    if (a > 0)
                    {
                        dic.Add("status", "success");
                        context.Response.Write((new JavaScriptSerializer()).Serialize(dic));
                        context.Session["username"] = null; //修改密码后需重新登录
                        context.Session["group"] = null;
                    }
                }
            }
            else
            {
                dic.Add("status", "sesionErr");
                context.Response.Write((new JavaScriptSerializer()).Serialize(dic));
            }
        }

        //找回密码
        private void FindPWD(HttpContext context)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();

            
            string step = context.Request["step"];
            
            if(step=="1")
            {
                username=context.Request["username"];
                string sql1 = "select email,question,answer from User2 where username=@username";
                SqlParameter ps1 = new SqlParameter("@username", username);
                dt1 = DBAccess.ExecuteDataTable(sql1, ps1);
                if (dt1.Rows.Count > 0)
                {
                     dic.Add("status", "hasUsername");
                     dic.Add("question", dt1.Rows[0][1].ConvertObjToStr());                    
                }
                else
                {
                  dic.Add("status", "noUsername");
                }
                
            }
            else if (step == "2")
            {
                string answer = context.Request["answer"];
                if (dt1.Rows[0][2].ConvertObjToStr() == answer)
                {
                    string email = dt1.Rows[0][0].ConvertObjToStr();
                    string pwd = CreateRandomNum(6);
                    string sql3 = "update User2 set pwd=@pwd where username=@username";
                    SqlParameter[] ps3 = { 
                                     new SqlParameter("@username", username),
                                     new SqlParameter("@pwd", MD5(pwd))
                                     };
                    int a = DBAccess.ExecuteNonQuery(sql3, ps3);
                    if (a > 0)
                    {
                        dic.Add("status", "success");
                        //dic.Add("newPwd",pwd);
                        string emailHead = email.Substring(0, 2);
                        if (emailHead.Substring(1, 1) == "@")
                        {
                            emailHead = emailHead.Substring(0, 1);
                        }
                        string emailTail = email.Split('@')[1];
                        dic.Add("email", emailHead + "...@" + emailTail);
                        //sendMail("找回密码", null, "您的初始密码为：" + pwd+",请及时登录修改密码。", email);
                        
                    }
                }
                else
                {
                    dic.Add("status", "answerErr");
                }
            }
            else
            {
                dic.Add("status", "Error");
            }
            context.Response.Write((new JavaScriptSerializer()).Serialize(dic));
        }

        //MD5加密
        public string MD5(string source)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5"); ;
        }

        //邮件发送
        public static string sendMail(string topic, string filePath, string body, string receiveAddr)
        {
            string sendAddress = "cxf6910697@163.com";//发件者邮箱地址
            string sendPassword = "13903894653";//发件者邮箱密码
            string receiveAddress = receiveAddr;//收件人收箱地址
            string mailTopic = topic;//主题
            string mailAttachment = filePath;//附件
            string mailBody = body;//内容
            string[] sendUsername = sendAddress.Split('@');

            SmtpClient client = new SmtpClient("smtp." + sendUsername[1].ToString()); //设置邮件协议

            client.UseDefaultCredentials = false;//这一句得写前面
            //client.EnableSsl = true;//服务器不支持SSL连接

            client.DeliveryMethod = SmtpDeliveryMethod.Network; //通过网络发送到Smtp服务器

            client.Credentials = new NetworkCredential(sendUsername[0].ToString(), sendPassword); //通过用户名和密码 认证
            MailMessage mmsg = new MailMessage(new MailAddress(sendAddress), new MailAddress(receiveAddress)); //发件人和收件人的邮箱地址
            mmsg.Subject = mailTopic;//邮件主题
            mmsg.SubjectEncoding = Encoding.UTF8;//主题编码
            mmsg.Body = mailBody;//邮件正文
            mmsg.BodyEncoding = Encoding.UTF8;//正文编码
            mmsg.IsBodyHtml = true;//设置为HTML格式 
            mmsg.Priority = MailPriority.High;//优先级
            if (mailAttachment.ConvertObjToStr() != "")
            {
                mmsg.Attachments.Add(new Attachment(mailAttachment));//增加附件
            }
            try
            {
                client.Send(mmsg);
                return null;
            }
            catch (Exception ee)
            {
                return ee.Message;
            }
        }

        //产生随机密码
        private string CreateRandomNum(int NumCount)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
            string[] allCharArray = allChar.Split(',');//拆分成数组
            string randomNum = "";
            int temp = -1;                             //记录上次随机数的数值，尽量避免产生几个相同的随机数
            Random rand = new Random();
            for (int i = 0; i < NumCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(35);
                if (temp == t)
                {
                    return CreateRandomNum(NumCount);
                }
                temp = t;
                randomNum += allCharArray[t];
            }
            return randomNum;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}